﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WHW_NetUtility;
using System.Runtime.Serialization.Formatters.Binary;
using MotionControl;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;

namespace MainFrame
{
    public partial class FormType : Form
    {
        typeData typedata;  //实例化类型数据
        string saveFilePath = "";
        string tempFpath = "";//打开数据路径
        string tempLpath = "";//打开数据路径
        CardMotion cardm;

        public FormType()
        {
            InitializeComponent();
        }

        public void TextBoxEnable(bool enable)
        {
            tbx_continualNumber.Enabled = enable;
            tbx_correctMagneticVelRate.Enabled = enable;
            tbx_correctMagneticW.Enabled = enable;
            tbx_correctMagneticY.Enabled = enable;
            tbx_correctMagneticZ.Enabled = enable;
            tbx_correctTimeout.Enabled = enable;
            tbx_getMagneticVelRate.Enabled = enable;
            tbx_getMagneticW.Enabled = enable;
            tbx_getMagneticY.Enabled = enable;
            tbx_getMagneticZ.Enabled = enable;
            tbx_laminateMagneticVelRate.Enabled = enable;
            tbx_laminateMagneticW.Enabled = enable;
            tbx_laminateMagneticY.Enabled = enable;
            tbx_laminateMagneticZ.Enabled = enable;
            tbx_precentErrorNumber.Enabled = enable;
            tbx_precentTotal.Enabled = enable;
            tbx_pullLength.Enabled = enable;
            tbx_takeFilmStepLength.Enabled = enable;
            tbx_takeUpFilmVelRate.Enabled = enable;
            tbx_takeUpFilmX.Enabled = enable;
            tbx_turnplateTimeout.Enabled = enable;
            tbx_ZsafePosition.Enabled = enable;
            tbx_TypeFile.Enabled = enable;
            tbx_pullSensorTimeout.Enabled = enable;
            tbx_magneticStep.Enabled = enable;
            tbx_suckerTimeout.Enabled = enable;
            tbx_resuckTimes.Enabled = enable;
            tbx_correctTimeout.Enabled = enable;

            btn_deleteAMname.Enabled = enable;
            btn_loadType.Enabled = enable;
            btn_newType.Enabled = enable;
            btn_saveType.Enabled = enable;
            btn_SaveAsType.Enabled = enable;
        }


        public string GetTemplateImagePath(string tempFilePath)
        {
            string temp;
            try
            {
                if (string.IsNullOrEmpty(tbx_TypeFile.Text.Trim()))
                {
                    //displalyInfo.displayInfoMain("请选择或新建型号文件再操作");
                    return "";
                }
                else
                {
                    int lastIndex = tbx_TypeFile.Text.Trim().LastIndexOf("\\");
                    temp = tbx_TypeFile.Text.Trim().Substring(0, lastIndex) + "\\" + tempFilePath;
                    return temp;
                    //displalyInfo.displayInfoMain(tempPath);
                }
            }
            catch (System.Exception ex)
            {
                return "";
            }
            
        }
        /// <summary>
        /// 判断RadioButton哪个项是选中的，并返回选中项的文本
        /// </summary>
        /// <param name="gb"></param>
        /// <param name="rbnText"></param>
        public void rbnControlChecked(GroupBox gb, out string rbnText)
        {
            rbnText = "";
            foreach (var item in gb.Controls)
            {
                if (item is RadioButton)
                {
                    if (((RadioButton)item).Checked)
                    {
                        rbnText = ((RadioButton)item).Text;
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 将当前控件的参数写到对象实例中
        /// </summary>
        public bool ControlToClass()
        {
            try
            {
                #region 取磁片
                //取磁片设置;
                GlobalVar.typedata_g.getMagneticY = Convert.ToDouble(tbx_getMagneticY.Text.Trim());//取磁片Y坐标
                GlobalVar.typedata_g.getMagneticZ = Convert.ToDouble(tbx_getMagneticZ.Text.Trim());//取磁片Z坐标
                GlobalVar.typedata_g.getMagneticW = Convert.ToDouble(tbx_getMagneticW.Text.Trim());//取磁片W坐标
                GlobalVar.typedata_g.getMagneticVelRate = Convert.ToDouble(tbx_getMagneticVelRate.Text.Trim());//取磁片运动速度比率
                #endregion

                #region 校正磁片
                //校正磁片设置;
                GlobalVar.typedata_g.correctMagneticY = Convert.ToDouble(tbx_correctMagneticY.Text.Trim());//校正磁片Y坐标
                GlobalVar.typedata_g.correctMagneticZ = Convert.ToDouble(tbx_correctMagneticZ.Text.Trim());//校正磁片Z坐标
                GlobalVar.typedata_g.correctMagneticW = Convert.ToDouble(tbx_correctMagneticW.Text.Trim());//校正磁片W坐标
                GlobalVar.typedata_g.correctMagneticVelRate = Convert.ToDouble(tbx_correctMagneticVelRate.Text.Trim());//校正磁片运动速度比率
                #endregion

                #region 贴合磁片
                //贴合磁片设置;
                GlobalVar.typedata_g.laminateMagneticY = Convert.ToDouble(tbx_laminateMagneticY.Text.Trim());//贴合磁片Y坐标
                GlobalVar.typedata_g.laminateMagneticZ = Convert.ToDouble(tbx_laminateMagneticZ.Text.Trim());//贴合磁片Z坐标
                GlobalVar.typedata_g.laminateMagneticW = Convert.ToDouble(tbx_laminateMagneticW.Text.Trim());//贴合磁片W坐标
                GlobalVar.typedata_g.laminateMagneticVelRate = Convert.ToDouble(tbx_laminateMagneticVelRate.Text.Trim());//贴合磁片运动速度比率
                #endregion


                #region 撕膜
                //撕膜磁片设置;
                GlobalVar.typedata_g.wipeoffMagneticX = Convert.ToDouble(tbx_takeUpFilmX.Text.Trim());//撕膜X坐标
                GlobalVar.typedata_g.wipeoffMagneticVelRate = Convert.ToDouble(tbx_takeUpFilmVelRate.Text.Trim());//撕膜速率
                GlobalVar.typedata_g.takeFilmPullLength = Convert.ToDouble(tbx_takeFilmStepLength.Text.Trim());//撕膜拉料长度
                #endregion

                #region 拉料设置
                //拉料设置
                GlobalVar.typedata_g.pullLength = Convert.ToDouble(tbx_pullLength.Text.Trim());//拉料长度
                GlobalVar.typedata_g.Fvacuss = cbx_vaccumF.Checked;//前负压是否检测
                GlobalVar.typedata_g.Mvacuss = cbx_vaccumM.Checked;//中负压是否检测
                GlobalVar.typedata_g.Lvacuss = cbx_vaccumL.Checked;//后负压是否检测
                #endregion

                #region 异常报警设置

                GlobalVar.typedata_g.isContinualError = cbx_continualError.Checked;
                GlobalVar.typedata_g.isPrecentError = cbx_precentError.Checked;
                GlobalVar.typedata_g.precentErrorTotal = (int)Math.Floor(Convert.ToDouble(tbx_precentTotal.Text.Trim()));
                GlobalVar.typedata_g.precentErrorNumber= (int)Math.Floor(Convert.ToDouble(tbx_precentErrorNumber.Text.Trim()));
                GlobalVar.typedata_g.continualNumber = (int)Math.Floor(Convert.ToDouble(tbx_continualNumber.Text.Trim()));
                #endregion

                GlobalVar.typedata_g.ZsafePosition = Convert.ToDouble(tbx_ZsafePosition.Text.Trim());
                GlobalVar.typedata_g.magneticAutoRise = cbx_magneticAutoRise.Checked;

                GlobalVar.typedata_g.turnplateTimeout = Convert.ToInt32(tbx_turnplateTimeout.Text.Trim());
                if (rbn_upEffect.Checked)
                {
                    GlobalVar.typedata_g.effectValue = 1;
                }
                else
                {
                    GlobalVar.typedata_g.effectValue = 2;
                }
                if (rbn_pullSensorUpEffect.Checked)
                {
                    GlobalVar.typedata_g.pullSensorUp = 1;
                }
                else
                {
                    GlobalVar.typedata_g.pullSensorUp = 2;
                }
                GlobalVar.typedata_g.magneticStep = Convert.ToDouble(tbx_magneticStep.Text.Trim());
                GlobalVar.typedata_g.isSuckerVaccum = cbx_isSuckerVaccum.Checked;
                GlobalVar.typedata_g.suckerTimeout = Convert.ToInt32(tbx_suckerTimeout.Text.Trim());
                GlobalVar.typedata_g.isResuck = cbx_isResuck.Checked;
                GlobalVar.typedata_g.resuckTimes = Convert.ToInt32(tbx_resuckTimes.Text.Trim());
                GlobalVar.typedata_g.correctTimeout = Convert.ToInt32(tbx_correctTimeout.Text.Trim());

                GlobalVar.typedata_g.isPullFixedLength = rbn_pullFixedLength.Checked;
                GlobalVar.typedata_g.pullSensorTimeout = Convert.ToInt32(tbx_pullSensorTimeout.Text.Trim());

                GlobalVar.typedata_g.PullIngoreLength = Convert.ToDouble(tbx_pullIngoreLength.Text.Trim());
                GlobalVar.typedata_g.IsLotsOfAM = cbx_isLotsOfAM.Checked;

                GlobalVar.typedata_g.PullFilmSensorTimes = Convert.ToInt16(tbx_pullLess.Text.Trim());
                GlobalVar.typedata_g.TakeFilmFrontSensorTimes = Convert.ToInt16(tbx_takeFilmLess.Text.Trim());
                GlobalVar.typedata_g.TakeFilmBackSensorManyTimes = Convert.ToInt16(tbx_takeFilmMany.Text.Trim());
                GlobalVar.typedata_g.TakeFilmBackSensorMoreTimes = Convert.ToInt16(tbx_takeFilmMore.Text.Trim());

                GlobalVar.typedata_g.RewindCylinderNumber = Convert.ToInt16(tbx_rewindCylinderTimes.Text.Trim());
                GlobalVar.typedata_g.RewindTotalNnumber = Convert.ToInt16(tbx_rewindNumber.Text.Trim());
                //GlobalVar.typedata_g = typedata;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("输入错误，请检查"+Environment.NewLine+ex.Message);
                Log4Helper.WriteLog("FormType.ParameterToClass", ex);
                return false;
            }
        }
        /// <summary>
        /// 将类中的数据，读取到控件中
        /// </summary>
        public void ClassToControl(typeData td)
        {
            try
            {
                #region 取磁片
                tbx_getMagneticY.Text=td.getMagneticY.ToString();//取磁片Y坐标
                tbx_getMagneticZ.Text=td.getMagneticZ.ToString();//取磁片Z坐标
                tbx_getMagneticW.Text=td.getMagneticW.ToString();//取磁片W坐标
                tbx_getMagneticVelRate.Text=td.getMagneticVelRate.ToString();//取磁片运动速度比率
                #endregion

                #region 校正磁片
                tbx_correctMagneticY.Text = td.correctMagneticY.ToString();//取磁片Y坐标
                tbx_correctMagneticZ.Text = td.correctMagneticZ.ToString();//取磁片Z坐标
                tbx_correctMagneticW.Text = td.correctMagneticW.ToString();//取磁片W坐标
                tbx_correctMagneticVelRate.Text = td.correctMagneticVelRate.ToString();//取磁片运动速度比率
                #endregion

                #region 贴合磁片
                tbx_laminateMagneticY.Text = td.laminateMagneticY.ToString();//贴合磁片Y坐标
                tbx_laminateMagneticZ.Text = td.laminateMagneticZ.ToString();//贴合磁片Z坐标
                tbx_laminateMagneticW.Text = td.laminateMagneticW.ToString();//贴合磁片W坐标
                tbx_laminateMagneticVelRate.Text = td.laminateMagneticVelRate.ToString();//贴合磁片运动速度比率
                #endregion

                #region 撕膜
                tbx_takeFilmStepLength.Text = td.takeFilmPullLength.ToString();//撕膜拉料长度
                tbx_takeUpFilmVelRate.Text = td.wipeoffMagneticVelRate.ToString();//撕膜拉料速率
                tbx_takeUpFilmX.Text = td.wipeoffMagneticX.ToString();//撕膜X坐标
                #endregion

                #region 拉料设置
                //拉料设置
                tbx_pullLength.Text=td.pullLength.ToString();//拉料长度
                cbx_vaccumF.Checked=td.Fvacuss;//前负压是否检测
                cbx_vaccumM.Checked=td.Mvacuss;//中负压是否检测
                cbx_vaccumL.Checked=td.Lvacuss;//后负压是否检测
                #endregion

                #region ErrorWaringTips
                cbx_continualError.Checked = td.isContinualError;
                cbx_precentError.Checked = td.isPrecentError;
                tbx_continualNumber.Text = td.continualNumber.ToString();
                tbx_precentTotal.Text = td.precentErrorTotal.ToString();
                tbx_precentErrorNumber.Text = td.precentErrorNumber.ToString();

                #endregion

                tbx_ZsafePosition.Text = td.ZsafePosition.ToString();
                cbx_magneticAutoRise.Checked = td.magneticAutoRise;
                if (td.effectValue==1)
                {
                    rbn_upEffect.Checked=true;
                }
                else
                {
                    rbn_downEffect.Checked = true;
                }
                if (td.pullSensorUp == 1)
                {
                    rbn_pullSensorUpEffect.Checked = true;
                }
                else
                {
                    rbn_pullSensorDownEffect.Checked = true;
                }
                tbx_turnplateTimeout.Text = td.turnplateTimeout.ToString();

                tbx_magneticStep.Text = td.magneticStep.ToString();
                cbx_isSuckerVaccum.Checked = td.isSuckerVaccum;


                tbx_suckerTimeout.Text = td.suckerTimeout.ToString();

                tbx_resuckTimes.Text = td.resuckTimes.ToString();
                cbx_isResuck.Checked = td.isResuck;

                tbx_correctTimeout.Text = td.correctTimeout.ToString();

                rbn_pullFixedLength.Checked = td.isPullFixedLength;
                rbn_pullSensor.Checked = !td.isPullFixedLength;
                tbx_pullSensorTimeout.Text = td.pullSensorTimeout.ToString();

                tbx_pullIngoreLength.Text = td.PullIngoreLength.ToString();

                cbx_isLotsOfAM.Checked = td.IsLotsOfAM;

                tbx_pullLess.Text = td.PullFilmSensorTimes.ToString();
                tbx_takeFilmLess.Text = td.TakeFilmFrontSensorTimes.ToString();
                tbx_takeFilmMany.Text = td.TakeFilmBackSensorManyTimes.ToString();
                tbx_takeFilmMore.Text = td.TakeFilmBackSensorMoreTimes.ToString();

                tbx_rewindNumber.Text = td.RewindTotalNnumber.ToString();
                tbx_rewindCylinderTimes.Text = td.RewindCylinderNumber.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取值错误，请检查" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormType.ClassToParameter", ex);
            }
        }

        private void btn_deleteAMname_Click(object sender, EventArgs e)
        {

        }

        private void btn_saveType_Click(object sender, EventArgs e)
        {
            //if (    GlobalImage.cablibData_Fweld.pixPerReal==0|| GlobalImage.cablibData_Lweld.pixPerReal == 0 || GlobalImage.cablibData_Measure.pixPerReal == 0)
            //{
            //    displalyInfo.displayInfoMain("相机没有标定，请先标定！！！");
            //    return;
            //}
            saveFilePath = tbx_TypeFile.Text.Trim();
            ControlToClass();
            SerializeFile();
            //设置输入口3，转盘到位检测开关的变化次数条件

            setIoCount();
            displalyInfo.displayInfoMain("型号保存成功");
        }

        public void setIoCount()
        {
            
        }

        private void AutoLoadTemplate()
        {
            try
            {
                string temp;
                tbx_TypeFile.Text = GlobalVar.autoload.TemplateFilePath;
                saveFilePath = GlobalVar.autoload.TemplateFilePath;
                temp = (saveFilePath.Substring(saveFilePath.LastIndexOf("\\") + 1));
                tbx_TypeName.Text = temp.Substring(0, temp.LastIndexOf("."));
                tbx_TypeFile.Text = saveFilePath;
                DeserializeFile();
                GlobalVar.typeDataOK = true;
                gbxEnabled(true);
                setIoCount();
                displalyInfo.displayInfoMain("型号载入成功");
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("载入文件出错：" + ex.Message);
            }

        }
        public void DeserializeFile_AutoLoad()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(Environment.CurrentDirectory + "\\autoload.ald", FileMode.Open))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    GlobalVar.autoload = saveFileBF.Deserialize(fs_serial) as AutoLoad;
                    cbx_autoLoad.Checked = GlobalVar.autoload.IsAutoLoad;
                    tbx_TypeFile.Text = GlobalVar.autoload.TemplateFilePath;
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.DeserializeFile", ex);
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        public void DeserializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(saveFilePath, FileMode.Open))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    typeData typed = saveFileBF.Deserialize(fs_serial) as typeData;
                    GlobalVar.typedata_g = typed;//传给全局变量
                    ClassToControl(typed);
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.DeserializeFile", ex);
            }
        }
        /// <summary>
        /// 序列化 listSuckerHead listSnap listFeeder
        /// </summary>
        public void SerializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(saveFilePath, FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    saveFileBF.Serialize(fs_serial, GlobalVar.typedata_g);
                    //typedata= GlobalVar.typedata_g;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("FormType.SerializeFile 序列化异常"+Environment.NewLine+ex.Message);
                Log4Helper.WriteLog("FormType.SerializeFile", ex);
            }
        }
        public void SerializeFile(string path)
        {
            try
            {
                using (FileStream fs_serial = new FileStream(path, FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    saveFileBF.Serialize(fs_serial, GlobalVar.typedata_g);
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.SerializeFile", ex);
            }
        }
        private void btn_newType_Click(object sender, EventArgs e)
        {
            if (tbx_TypeName.Text == "" || tbx_TypeName == null)
            {
                MessageBox.Show("新建型号文件，需要输入型号名称", "提示");
            }
            else
            {
                FolderBrowserDialog AMtype_FBD = new FolderBrowserDialog();
                AMtype_FBD.Description = "选择新建辅料类型文件路径";
                //AMtype_FBD.RootFolder = Environment.SpecialFolder.MyComputer;
                AMtype_FBD.RootFolder =System.Environment.SpecialFolder.MyComputer;
                if (AMtype_FBD.ShowDialog() == DialogResult.OK)
                {
                    saveFilePath = AMtype_FBD.SelectedPath +"\\"+ tbx_TypeName.Text + ".AMM";
                    tbx_TypeFile.Text = saveFilePath;
                    displalyInfo.displayInfoMain("新建型号文件成功，型号路径为："+Environment.NewLine+saveFilePath);
              

                    GlobalVar.typeDataOK=true;
                    GlobalVar.isROIdisplay = true;
                    gbxEnabled(true);
                }
            }
        }

        private void FormType_Load(object sender, EventArgs e)
        {
            //GlobalVar.TIS_Acq.IcControl.ImageAvailable += new EventHandler<ICImagingControl.ImageAvailableEventArgs>(ImageAvailableEvent);
            DeserializeFile_AutoLoad();
            if (GlobalVar.autoload.IsAutoLoad)
            {
                AutoLoadTemplate();
            }
            //typedata = new typeData();
            displalyInfo.displayInfoMain("型号数据初始化");
            //typeFileDisplay();
            //开始采集
            //cardm = (CardMotion)GlobalVariable.ListCard[0];
            gbxEnabled(false);

            bool status = false;
            //HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 0, 6, ref status);
            if (!status)
            {
                btn_takeFilmCylinder.BackColor = Color.Gray;
            }
            else
            {
                btn_takeFilmCylinder.BackColor = Color.Green;
            }
            if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.operatorStaff)
            {
                TextBoxEnable(false);
                TypeEnable_operate(false);
            }
            else
            {
                TextBoxEnable(true);
                TypeEnable_operate(true);
            }
            //changeUser.changeUserID += TextBoxEnable;
            changeUser.changeUserID += TypeEnable_operate;
        }

        public void gbxEnabled(bool isEnabled)
        {
            gbx_pull.Enabled = isEnabled;
            gbx_weld.Enabled = isEnabled;
            gbx_turnplateSetup.Enabled = isEnabled;
            gbx_takeFilm.Enabled = isEnabled;
            gbx_correct.Enabled = isEnabled;
            gbx_laminate.Enabled = isEnabled;
        }

        public void TypeEnable_operate(bool isEnable)
        {
            gbx_pull.Enabled = isEnable;
            gbx_weld.Enabled = isEnable;
            gbx_turnplateSetup.Enabled = isEnable;
            gbx_takeFilm.Enabled = isEnable;
            gbx_correct.Enabled = isEnable;
            gbx_laminate.Enabled = isEnable;
            gbx_typeOperate.Enabled = isEnable;
            gbx_safe.Enabled = isEnable;
            gbx_resucker.Enabled = isEnable;
            
        }
        public void typeFileDisplay()
        {
            if (tbx_TypeName.Text != "")
            {
                tbx_TypeFile.Text =Environment.CurrentDirectory+"\\"+ tbx_TypeName.Text + ".AMM";
            }
            else
            {
                tbx_TypeFile.Text = "";
            }
        }
        private void tbx_TypeName_TextChanged(object sender, EventArgs e)
        {
            typeFileDisplay();
        }

        private void btn_loadType_Click(object sender, EventArgs e)
        {
            try
            {
                string temp;
                OpenFileDialog typeFile_ofd = new OpenFileDialog();
                typeFile_ofd.Title = "选择类型文件存放的路径";
                typeFile_ofd.InitialDirectory = Environment.CurrentDirectory+"\\TypeData";
                typeFile_ofd.Filter = "AMM Files(*.AMM)|*.AMM|All Files(*.*)|*.*";
                if (typeFile_ofd.ShowDialog() == DialogResult.OK)
                {
                    saveFilePath = typeFile_ofd.FileName;
                    temp = (saveFilePath.Substring(saveFilePath.LastIndexOf("\\") + 1));
                    tbx_TypeName.Text = temp.Substring(0, temp.LastIndexOf("."));
                    tbx_TypeFile.Text = saveFilePath;
                    DeserializeFile();

                    Thread.Sleep(200);
                
                    if (string.IsNullOrEmpty(tempFpath)||string.IsNullOrEmpty(tempLpath))
                    {
                        displalyInfo.displayInfoMain("模板文件载入不成功,请重新创建模板！！！！！！");
                        return;
                    }
                    
                    #region 注释掉
                    //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Fweld.cameraSerial))
                    //{
                    //    if (GlobalImage.hik_Fweld == null)
                    //    {
                    //        GlobalImage.hik_Fweld = new HikVision(GlobalImage.cablibData_Fweld.cameraSerial);
                    //        GlobalImage.hik_Fweld.imageOut = visionProc.Fweld;
                    //    }
                    //}
                    //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Lweld.cameraSerial))
                    //{
                    //    if (GlobalImage.hik_Lweld == null)
                    //    {
                    //        GlobalImage.hik_Lweld = new HikVision(GlobalImage.cablibData_Lweld.cameraSerial);
                    //        GlobalImage.hik_Lweld.imageOut = visionProc.Lweld;
                    //    }
                    //}
                    //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Measure.cameraSerial))
                    //{
                    //    if (GlobalImage.hik_Meausre == null)
                    //    {
                    //        GlobalImage.hik_Meausre = new HikVision(GlobalImage.cablibData_Measure.cameraSerial);
                    //        GlobalImage.hik_Meausre.imageOut = visionProc.measure;
                    //    }

                    //}
                    #endregion
                    GlobalVar.typeDataOK = true;
                    gbxEnabled(true);
                    //设置输入口3，转盘到位检测开关的变化次数条件
                    setIoCount();

                    displalyInfo.displayInfoMain("型号载入成功");
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("载入文件出错："+ex.Message);
            }
            
        }

        private void btn_SaveAsType_Click(object sender, EventArgs e)
        {
            SaveFileDialog typeFile_sfd = new SaveFileDialog();
            typeFile_sfd.Title = "选择类型文件另存为的路径";
            typeFile_sfd.InitialDirectory = Environment.CurrentDirectory;
            typeFile_sfd.Filter = "AMM Files(*.AMM)|*.AMM|All Files(*.*)|*.*";
            if (typeFile_sfd.ShowDialog() == DialogResult.OK)
            {
                SerializeFile(typeFile_sfd.FileName);
                displalyInfo.displayInfoMain("另存为型号文件成功");
            }
            else
            {
                displalyInfo.displayInfoMain("另存为型号文件取消");
            }
        }


        private void tbx_F_weld_X_TextChanged(object sender, EventArgs e)
        {
            setControlValue(tbx_getMagneticY, 0);            
        }

        private void tbx_F_weld_Y_TextChanged(object sender, EventArgs e)
        {
            setControlValue(tbx_getMagneticZ, 1);
        }

        private void setControlValue(TextBox tbx,int axisNo)
        {
            try
            {
                double currentValue = Convert.ToDouble(tbx.Text.Trim());
                double softPosLimit = ((AxisServo)GlobalMotion.mainCard.AxisList[axisNo]).m_SoftPosLimit;
                double softNegLimit = ((AxisServo)GlobalMotion.mainCard.AxisList[axisNo]).m_SoftNegLimit;
                if (currentValue > softNegLimit && currentValue < softPosLimit)
                {
                    ControlToClass();
                }
                else
                {
                    displalyInfo.displayInfoMain("输入的值超过当前轴的软限位");
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("请输入符合要求值");
                displalyInfo.displayInfoMain("错误信息是：" + ex.Message);
                Log4Helper.WriteLog("FormType.setControlValue", ex);
            }
        }
        private void setControlValue(TextBox tbx, double low, double high,string error)
        {
            try
            {
                double F_weld_X = Convert.ToDouble(tbx.Text.Trim());
                if (F_weld_X > low && F_weld_X <= high)
                {
                    ControlToClass();
                }
                else
                {
                    displalyInfo.displayInfoMain("输入的值不符合要求："+error);
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("请输入符合要求值");
                displalyInfo.displayInfoMain("错误信息是：" + ex.Message);
                Log4Helper.WriteLog("FormType.setControlValue", ex);
            }
        }
        private void setControlValue(TextBox tbx, double low, double high)
        {
            try
            {
                double F_weld_X = Convert.ToDouble(tbx.Text.Trim());
                if (F_weld_X > low && F_weld_X <= high)
                {
                    ControlToClass();
                }
                else
                {
                    displalyInfo.displayInfoMain("输入的值不符合要求");
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("请输入符合要求值");
                displalyInfo.displayInfoMain("错误信息是：" + ex.Message);
                Log4Helper.WriteLog("FormType.setControlValue", ex);
            }
        }


        private void tbx_pullLength_TextChanged(object sender, EventArgs e)
        {
            setControlValue(tbx_pullLength, 0, 1000, "拉料长度0-1000mm");
            //displalyInfo.displayInfoMain("拉料长度0-1000mm");
        }


        private void cbx_vaccumF_CheckedChanged(object sender, EventArgs e)
        {
            ControlToClass();
        }

        /// <summary>
        /// 获取轴的值并更新到控件上
        /// </summary>
        /// <param name="tbx">文本控件</param>
        /// <param name="tbx1">文本控件</param>
        /// <param name="axisNo">文本控件对应的轴</param>
        /// <param name="axisNoTwo">文本控件1对应的轴</param>
        private void getAxisAndSet(TextBox tbx,TextBox tbx1,TextBox tbx2,int axisNo,int axisNoTwo,int axisNoThree)
        {
            try
            {
                string[] axisCurrentValue;
                axisCurrentValue = GlobalMotion.getCurrent();
                if (axisCurrentValue != null)
                {
                    tbx.Text = axisCurrentValue[axisNo];
                    tbx1.Text = axisCurrentValue[axisNoTwo];
                    tbx2.Text = axisCurrentValue[axisNoThree];
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("FormType.getAxisAndSet"+ex.Message);
            }
        }


        private void btn_startPull_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => GlobalMotion.mainCard.AxisList[5].PointMove(GlobalVar.typedata_g.pullLength,true));

        }

        private void btn_stopPull_Click(object sender, EventArgs e)
        {
            GlobalMotion.mainCard.AxisList[5].AxisStop();
        }

        private void btn_getPosi_get_Click(object sender, EventArgs e)
        {
            getAxisAndSet(tbx_getMagneticY,tbx_getMagneticZ,tbx_getMagneticW,1,3,4);
        }

        private void btn_getPosi_correct_Click(object sender, EventArgs e)
        {
            getAxisAndSet(tbx_correctMagneticY, tbx_correctMagneticZ, tbx_correctMagneticW, 1, 3, 4);
        }

        private void btn_getPosi_laminate_Click(object sender, EventArgs e)
        {
            getAxisAndSet(tbx_laminateMagneticY, tbx_laminateMagneticZ, tbx_laminateMagneticW, 1, 3, 4);
        }



        private void btn_ToPosi_get_Click(object sender, EventArgs e)
        {
            GlobalMotion.ToPosition_Get();
        }

        private void btn_ToPosi_correct_Click(object sender, EventArgs e)
        {
            
        }

        private void btn_correctMagnetic_Click(object sender, EventArgs e)
        {
            
        }

        private void btn_ToPosi_laminate_Click(object sender, EventArgs e)
        {
            
        }


        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
        }

        private void tbx_getMagneticY_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_getMagneticY, 1);
            }
        }

        private void tbx_getMagneticZ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_getMagneticZ, 3);
            }
        }

        private void tbx_getMagneticVelRate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_getMagneticVelRate, 0, 1);
            }
        }

        private void tbx_correctMagneticY_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_correctMagneticY, 1);
            }
        }

        private void tbx_correctMagneticZ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_getMagneticZ, 3);
            }
        }

        private void tbx_correctMagneticVelRate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_correctMagneticVelRate, 0, 1);
            }
           
        }

        private void tbx_laminateMagneticVelRate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_laminateMagneticVelRate, 0, 1);
            }
        }

        private void btn_takeFilmCylinder_Click(object sender, EventArgs e)
        {
           
        }

        private void btn_turnplateRotate_Click(object sender, EventArgs e)
        {
           
        }

        private void tbx_takeUpFilmVelRate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_takeUpFilmVelRate, 0, 20);
            }
        }

        private void tbx_takeFilmStepLength_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_takeFilmStepLength, 0, 1000, "撕膜拉料长度0-1000mm");
            }
        }

        private void tbx_takeUpFilmX_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                setControlValue(tbx_takeUpFilmX, 0);
            }
        }

        private void btn_getMagnetic_Click(object sender, EventArgs e)
        {
           
        }

        private void btn_laminateMagnetic_Click(object sender, EventArgs e)
        {
           
        }

        private void btn_magneticRise_Click(object sender, EventArgs e)
        {
                
        }

        private void btn_takeFilmPull_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => GlobalMotion.mainCard.AxisList[6].PointMove(GlobalVar.typedata_g.pullLength, false));
        }

        private void btn_takeFilmStop_Click(object sender, EventArgs e)
        {
            GlobalMotion.mainCard.AxisList[6].AxisStop();
        }

        private void tbx_magneticStep_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_magneticStep, 2);
            }
        }

        private void tbx_turnplateTimeout_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_turnplateTimeout, 1);
            }
        }

        private void tbx_ZsafePosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_ZsafePosition, 1);
            }
        }

        private void cbx_magneticAutoRise_CheckedChanged(object sender, EventArgs e)
        {
            ControlToClass();
        }

        private void cbx_isSuckerVaccum_CheckedChanged(object sender, EventArgs e)
        {
            ControlToClass();
        }

        private void tbx_resuckTimes_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_resuckTimes, 1,100);
            }
        }

        private void tbx_suckerTimeout_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_suckerTimeout, 0,10000);
            }
        }

        private void tbx_laminateMagneticY_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_laminateMagneticY, 1);
            }
        }

        private void tbx_laminateMagneticZ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_laminateMagneticZ, 3);
            }
        }

        private void tbx_laminateMagneticW_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setControlValue(tbx_laminateMagneticW, 4);
            }
        }

        private void btn_ToPosi_WipeoffFilm_Click(object sender, EventArgs e)
        {
         
        }

        private void btn_wipeoffFilm_Click(object sender, EventArgs e)
        {
            
        }

 

        private void btn_clampFilmCylinder_Click(object sender, EventArgs e)
        {

        }

        private void btn_pressFilmCylinder_Click(object sender, EventArgs e)
        {

        }

        private void rbn_upEffect_CheckedChanged(object sender, EventArgs e)
        {
            if (rbn_upEffect.Checked)
            {
                GlobalVar.typedata_g.effectValue = 1;
            }
            else
            {
                GlobalVar.typedata_g.effectValue = 2;
            }
            if (rbn_pullSensorUpEffect.Checked)
            {
                GlobalVar.typedata_g.pullSensorUp = 1;
            }
            else
            {
                GlobalVar.typedata_g.pullSensorUp = 2;
            }
            setIoCount();
        }

        private void cbx_isLotsOfAM_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.checkIsLotsOfAM = cbx_isLotsOfAM.Checked;
        }

        private void cbx_isAutoRunThreadTips_CheckedChanged(object sender, EventArgs e)
        {
            if (cbx_isAutoRunThreadTips.Checked)
            {
                GlobalVar.isAutoRunThreadTips = true;
            }
            else
            {
                GlobalVar.isAutoRunThreadTips = false;
            }
        }

        private void btn_filmAlarmTakeoff_Click(object sender, EventArgs e)
        {
            Interlocked.Exchange(ref GlobalVar.currentCircleTakeNumber_BackMany, 0);
            Interlocked.Exchange(ref GlobalVar.currentCircleTakeNumber_BackMore, 0);
            Interlocked.Exchange(ref GlobalVar.currentCircleTakeNumber, 0);
            Interlocked.Exchange(ref GlobalVar.currentCirclePullNumber, 0);
            GlobalVar.isHaveAlarm = false;
        }

        private void cbx_autoLoad_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.autoload.IsAutoLoad = cbx_autoLoad.Checked;
        }
        public void SerializeFile_AutoLoad()
        {
            try
            {
                GlobalVar.autoload.IsAutoLoad = cbx_autoLoad.Checked;
                GlobalVar.autoload.TemplateFilePath = tbx_TypeFile.Text.Trim();
                using (FileStream fs_serial = new FileStream(Environment.CurrentDirectory + "\\autoLoad.ald", FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    saveFileBF.Serialize(fs_serial, GlobalVar.autoload);
                    //GlobalVar.typedata_g = GlobalVar.typedata_g;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("FormType.SerializeFile 序列化异常" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormType.SerializeFile", ex);
            }
        }
        private void FormType_FormClosing(object sender, FormClosingEventArgs e)
        {
            SerializeFile_AutoLoad();
        }

        private void tbx_rewindNumber_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (tbx_rewindNumber.Text=="")
                {
                    return;
                }
                GlobalVar.typedata_g.RewindTotalNnumber = Convert.ToInt16(tbx_rewindNumber.Text.Trim());
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private void tbx_rewindCylinderTimes_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (tbx_rewindCylinderTimes.Text == "")
                {
                    return;
                }
                GlobalVar.typedata_g.RewindCylinderNumber = Convert.ToInt16(tbx_rewindCylinderTimes.Text.Trim());
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }
    }
}
